/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * <p>Project: javaseapp - Demo
 * <p>Powered by webrx On 2021-08-20 11:48:51
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */

public class Demo {
    @Test
    public void test() {
        Map<String, Integer> maps = new TreeMap<String, Integer>();
        maps.put("张三", 22);
        maps.put("李四", 24);
        maps.put("王五", 18);
        maps.put("赵六", 28);
        maps.put("张三丰", 32);
        maps.put("李丽", 21);
        System.out.println(maps);

        //自定义比较器  Map.Entry 相当于 Student(name,age)
        Comparator<Map.Entry<String, Integer>> valCmp = new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue() - o1.getValue();  // 降序排序，如果想升序就反过来
            }
        };

        // 降序排序，如果想升序就反过来
        Comparator<Map.Entry<String, Integer>> com = (o1, o2) -> o2.getValue() - o1.getValue();


        //将map转成List，map的一组key，value对应list一个存储空间
        var list = new ArrayList<Map.Entry<String, Integer>>(maps.entrySet()); //传入maps实体
        //Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); // 注意此处Collections 是java.util包下面的,传入List和自定义的valCmp比较器
        //根据值来排序
        list.sort(Comparator.comparingInt(Map.Entry::getValue));

        System.out.println(list);

        //根据key来排序,其它TreeMap默认是根据key排序升序
        list.sort((a, b) -> b.getKey().compareTo(a.getKey()));

        for (Map.Entry<String, Integer> e : list) {
            System.out.printf("%s = %d%n", e.getKey(), e.getValue());
        }
        //输出map
        //for (int i = 0; i < list.size(); i++) {
        //    System.out.println(list.get(i).getKey() + " = " + list.get(i).getValue());
        //}
    }
}
